package com.rpframework.module.common.bottom.controller;


import com.rpframework.core.json.JsonResp;
import com.rpframework.core.json.ParameterException;
import com.rpframework.module.common.bottom.entity.Express;
import com.rpframework.module.common.bottom.service.ExpressService;
import com.rpframework.module.common.service.UserTokenService;
import com.rpframework.module.common.url.RequestDescription;
import com.rpframework.utils.OkHttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@ResponseBody
@RequestMapping
@RequestDescription("快递相关")
@Controller
public class ExpressController extends BaseController {

    private final ExpressService expressService;

    @Autowired
    public ExpressController(UserTokenService uerTokenService, ExpressService expressService) {
        super(uerTokenService);
        this.expressService = expressService;
    }

    @RequestDescription("所有快递列表")
    @RequestMapping
    public JsonResp<List<Express>> allList() {
        return expressService.selectAllJson();
    }

    @RequestDescription("物流信息查询")
    @RequestMapping
    public JsonResp<String> physicalInfo(Express express) throws IOException {
        Long id = express.getId();
        String code = express.getCode();
        String number = express.getNumber();
        if (id == null && StringUtils.isBlank(code) || StringUtils.isBlank(number)) {
            throw new ParameterException("(物流代码|物流主键)二选一/物流单号不能为空");
        }
        if (StringUtils.isBlank(code)) {
            code = expressService.selectPrimaryKeyInspect(id).getCode();
        }
        List<BasicNameValuePair> p = new ArrayList<>();
        p.add(new BasicNameValuePair("type", code));
        p.add(new BasicNameValuePair("postid", number));
        return new JsonResp<String>().data(OkHttpUtil.post("http://www.kuaidi100.com/query", p));
    }

}
